<script setup lang="ts">
import { nextTick, ref } from "vue";
import { ITableData, IScopeFormState } from "./types.ts";
import FormItem from "@/components/autoForm/FormItem.ts";
import { scopeFormState, scopeOptions } from "./data.ts";
import { addRow } from "@/api/common";

const emit = defineEmits(["refresh"]);
const modalRef = ref();
const formRef = ref();
const confirmLoading = ref(false);

const openAddModal = (row: ITableData) => {
  modalRef.value.openModal();
  nextTick(() => {
    scopeFormState.roleId = row.roleId;
    scopeFormState.roleName = row.roleName;
    scopeFormState.roleKey = row.roleKey;
    scopeFormState.dataScope = row.dataScope || "";
  });
};
defineExpose({ openAddModal });

const modalCancalHandle = () => {
  modalRef.value.closeModal();
  confirmLoading.value = false;
};
const modalSubmitHandle = () => {
  confirmLoading.value = true;
  addRow<IScopeFormState>("/system/role/dataScope", scopeFormState, "put")
    .then(() => {
      emit("refresh", {});
      modalCancalHandle();
    })
    .catch(() => (confirmLoading.value = false));
};
</script>

<template>
  <JModal title="分配数据权限" ref="modalRef" :footer="null" :width="600">
    <template #default>
      <a-form
        ref="formRef"
        layout="vertical"
        :model="scopeFormState"
        name="addForm"
        @finish="modalSubmitHandle"
      >
        <a-row :gutter="30">
          <template v-for="item in scopeOptions" :key="item">
            <a-col :span="item.span || 12">
              <a-form-item
                :label="item.label"
                :name="item.field"
                :rules="item.rules"
              >
                <FormItem
                  v-model:value="scopeFormState[item.field]"
                  :option="item"
                  style="width: 100%"
                ></FormItem>
              </a-form-item>
            </a-col>
          </template>
        </a-row>
        <div
          style="padding-bottom: 20px; display: flex; justify-content: flex-end"
        >
          <a-button @click="modalCancalHandle">取消</a-button>
          <a-button
            type="primary"
            style="margin-left: 10px"
            html-type="submit"
            :loading="confirmLoading"
          >
            确认
          </a-button>
        </div>
      </a-form>
    </template>
  </JModal>
</template>
